﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IRCBot.Messages;
using IRCBot.Helpers;
using HtmlAgilityPack;

namespace IRCBot.Modules
{
    public class PinterestModule : IModule
    {
        public event SendDataEvent SendData;
        public event SayEvent Say;
        public event DelayedSayEvent DelayedSay;
        public event ModuleEvent ClearDelayedMessages;

        private DateTime _timeOfLastPinterestRequest = new DateTime();

        public void HandleIncomingMessage(IncomingMessage message)
        {
            switch (message.Command.ToLower())
            {
                case ":!reference":
                    HandleReference(message);
                    break;
                case ":!random":
                    HandleRandom(message);
                    break;
            }
        }

        private void HandleRandom(IncomingMessage message)
        {
            GetRandomImageFromBoard(@"http://pinterest.com/jacobjohnson/sketchdaily-fun/", message);
        }

        private void HandleReference(IncomingMessage message)
        {
            GetRandomImageFromBoard(@"http://pinterest.com/artomizer/drawbot-reference/", message);
        }

        private void GetRandomImageFromBoard(string boardUrl, IncomingMessage message)
        {
            if (DateTime.Now >= _timeOfLastPinterestRequest.AddSeconds(20))
            {
                _timeOfLastPinterestRequest = DateTime.Now;
                string html = HTMLHelper.GetHtmlFromUrl(boardUrl, null, null);
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);

                HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//a[@class='PinImage ImgLink']");
                if (nodes != null)
                {
                    if (nodes.Count() > 0)
                    {
                        int randomIndex = RandomHelper.GetRandomNumber(0, nodes.Count() - 1);
                        HtmlNode node = nodes[randomIndex];
                        Say(@"http://www.pinterest.com" + node.Attributes["href"].Value, message.Channel);
                    }
                    else
                        Say("No images found.", message.Channel);
                }
            }
            else
                Say("Maximum number of requests reached. Please wait 20 seconds.", message.Channel);
        }
    }
}
